<?php

namespace App\Http\Controllers;

use DB;
use Auth;
use Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller
{
	/**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
	}
	
    public function uploadPicture(Request $request)
    {
		$user = Auth::user();
		
    	if ($request->isMethod('POST')) {

    		$file = $request->file('source');

    		$form = $request->request->all();

    		if ($file->isValid()) {
    			/*  
    			 *  laravel上传图片
	    			// 获取文件相关信息
	                $originalName = $file->getClientOriginalName(); 	// 文件原名
	                $ext = $file->getClientOriginalExtension();     	// 扩展名
	                $realPath = $file->getRealPath();   				//临时文件的绝对路径
	                $type = $file->getClientMimeType();     		 	// image/jpeg

	                // 上传文件
	                $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;

	                // 使用我们新建的uploads本地存储空间（目录）
	                $bool = Storage::disk('upload')->put($filename, file_get_contents($realPath));
    			*/

                $realPath = $file->getRealPath(); 
                $ext = $file->getClientOriginalExtension();

                //修改指定图片的大小
				$imgFull = Image::make($realPath);
				$imgCompress = Image::make($realPath)->resize(360, 220);

				// 插入水印, 水印位置在原图片的右下角, 距离下边距 10 像素, 距离右边距 15 像素
				// $img->insert('../storage/app/public/2.jpeg', 'bottom-right', 25, 20);

				// 插入文字
				// $imgFull->text('@xxm', 600, 375);
				// $imgCompress->text('@xxm', 180, 110);

				$filename = date('Y-m-d-H-i-s') . '-' . uniqid();
				$fullName = $filename . '-full' . '.' . $ext;
				$compressName = $filename . '-compress' . '.' . $ext;

				// 将处理后的图片重新保存到其他路径
				$fullBool = $imgFull->save('../storage/app/public/' . $fullName);
				$compressBool = $imgCompress->save('../storage/app/public/compress/' . $compressName);

				/* 上面的逻辑可以通过链式表达式搞定 */
				// $img = Image::make('images/avatar.jpg')->resize(200, 200)->insert('images/new_avatar.jpg', 'bottom-right', 15, 10);

                $createdTime = time();

         		// 添加到数据库
         		DB::table('pictures')->insert([
         			'name' => $fullName,
         			'picture_path' =>  $form['path'],
         			'title' => $form['title'],
         			'description' => $form['description'],
         			'compress_name' => $compressName,
         			'created_time' => $createdTime,
         			'updated_time' => $createdTime,
         		]);

            	// 	DB::insert('insert into `pictures` (name, picture_path, title, description, created_time, updated_time) values(?,?,?,?,?,?)',[$filename, $form['path'], $form['title'], $form['description'], $createdTime, $createdTime]);
            	// }

            	return redirect('/show');
            }
            
    	}

    	return view('admin.upload', array(
    		'user' => $user,
    	));
    }

    
}
